import { cancelOrder, takeOrder, delOrder, payOrder } from "@api/order";
import dialog from "@utils/dialog";
import { pay } from "@libs/wechat";
import router from "../router";

export function cancelOrderHandle(orderId) {
  return new Promise((resolve, reject) => {
    dialog.confirm({
      mes: "确认取消该订单?",
      opts() {
        cancelOrder(orderId)
          .then(res => {
            dialog.success("取消成功");
            resolve(res);
          })
          .catch(err => {
            dialog.error("取消失败");
            reject(err);
          });
      }
    });
  });
}

export function takeOrderHandle(orderId) {
  return new Promise((resolve, reject) => {
    takeOrder(orderId)
      .then(res => {
        resolve(res);
      })
      .catch(err => {
        dialog.error("收货失败");
        reject(err);
      });
  });
}

export function delOrderHandle(orderId) {
  return new Promise((resolve, reject) => {
    dialog.confirm({
      mes: "确认删除该订单?",
      opts() {
        delOrder(orderId)
          .then(res => {
            dialog.success("删除成功");
            resolve(res);
          })
          .catch(err => {
            dialog.error("删除失败");
            reject(err);
          });
      }
    });
  });
}

export function payOrderHandle(orderId, type, from,isIospay,oid) {
  return new Promise((resolve, reject) => {
    dialog.loading.open("");
    payOrder(orderId, type, from,isIospay,oid)
      .then(res => {
        const data = res.data;
        console.log(data.result.jsConfig);
        dialog.loading.close();
        switch (data.status) {
          case "WECHAT_H5_PAY":
            reject(data);
            setTimeout(() => {
              location.replace(data.result.jsConfig.mweb_url);
            }, 100);
            break;
          case "ORDER_EXIST":
          case "EXTEND_ORDER":
          case "PAY_ERROR":
          case "PAY_DEFICIENCY":
            dialog.toast({ mes: res.msg });
            reject(data);
            break;
          case "SUCCESS":
            dialog.success(res.msg);
            resolve(data);
            break;
          case "WECHAT_APP_PAY":
            var u = navigator.userAgent, app = navigator.appVersion;
            var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; //g
            var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
            var win = window;
            var obj={
                "action": "payBridge",//方法名
                "content": {
                    'type':type,//微信 aliPay//支付宝
                    'data':data.result//支付信息
                }
            }
            if (isAndroid){
                App.onAppResponse(JSON.stringify(obj));
            }
            if (isIOS) {
                win.webkit.messageHandlers.onAppResponse.postMessage(JSON.stringify(obj));
            }
            break;
          case "WECHAT_WXAPP_PAY":
          wx.miniProgram.navigateTo({ url: "/pages/pay/pay?prepay_id="+data.result.jsConfig.prepay_id+"&appid="+data.result.jsConfig.appid+"&nonce_str="+data.result.jsConfig.nonce_str+"&sign="+data.result.jsConfig.sign+"&sign_type="+data.result.jsConfig.sign_type+"&timeStamp="+data.result.jsConfig.timeStamp+"&orderId="+data.result.orderId,});
          break;
          case "ALI_APP_PAY":
            var u = navigator.userAgent, app = navigator.appVersion;
            var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; //g
            var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
            var win = window;
            var obj={
                "action": "payBridge",//方法名
                "content": {
                    'type':type,//微信 aliPay//支付宝
                    'data':data.result//支付信息
                }
            }
            if (isAndroid){
                App.onAppResponse(JSON.stringify(obj));
            }
            if (isIOS) {
                win.webkit.messageHandlers.onAppResponse.postMessage(JSON.stringify(obj));
            }
            break;
          case "ALI_H5_PAY":
            setTimeout(() => {
              location.href = data.result.jsConfig;
            }, 1);
            break;
          case "WECHAT_PAY":
            // pay(data.result.jsConfig).finally(() => {
              
            //   router.replace({
            //     path: "/order/status/" + data.result.order_id+"/4"
            //   });

            //   // window.location.href = "http://ds.h5.cbct.cn/order/status/" + data.result.order_id+"/4"
            // });
            WeixinJSBridge.invoke(
                  'getBrandWCPayRequest', {
                      "appId":data.result.jsConfig.appId,
                      "nonceStr":data.result.jsConfig.nonceStr,
                      "package":data.result.jsConfig.package,
                      "signType":data.result.jsConfig.signType,
                      "timeStamp":data.result.jsConfig.timestamp,
                      "paySign":data.result.jsConfig.paySign,
                  },
                
                  function (res) {
                    WeixinJSBridge.log(res.err_msg + 'err');
                      if (res.err_msg=='get_brand_wcpay_request:ok') {
                        router.replace({
                          path: "/order/status/" + data.result.order_id+"/4"
                        });
                      }else if(res.err_msg=='get_brand_wcpay_request:cancel'){
                        router.replace({
                          path: "/order/status/" + data.result.order_id+"/4"
                        });
                      }else{
                        router.replace({
                          path: "/order/status/" + data.result.order_id+"/4"
                        });
                      }
                  }
            );
            break;
        }
      })
      .catch(err => {
        dialog.loading.close();
        dialog.toast({ mes: err.msg || "订单支付失败" });
      });
  });
}

export function goShopDetail(item) {
  return new Promise(resolve => {
    if (item.activity && item.activity.type === "1") {
      router.push({
        path:
          "/activity/seckill_detail/" +
          item.activity.id +
          "/" +
          item.activity.time +
          "/1"
      });
    } else if (item.activity && item.activity.type === "2") {
      router.push({
        path: "/activity/dargain_detail/" + item.activity.id
      });
    } else if (item.activity && item.activity.type === "3") {
      router.push({
        path: "/activity/group_detail/" + item.activity.id
      });
    } else {
      resolve(item);
    }
  });
}
